package cn.bqjr.eily.samples.controller.common;

import cn.bqjr.eily.mybatis.spring.boot.utils.PagingUtils;
import cn.bqjr.eily.samples.controller.base.BaseController;
import cn.bqjr.eily.samples.entity.po.LoginLog;
import cn.bqjr.eily.samples.entity.po.User;
import cn.bqjr.eily.samples.service.base.ILoginLogService;
import cn.bqjr.eily.samples.service.commom.IAuthService;
import cn.bqjr.eily.shiro.spring.boot.entity.ShiroProperties;
import cn.bqjr.eily.utils.StringUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

@RestController
public class AuthController extends BaseController {
    @Autowired
    private ShiroProperties shiroProperties;

    @Autowired
    private IAuthService authService;

    @Autowired
    private ILoginLogService loginLogService;

    /**
     * 租户-用户登录
     * @param tenantId
     * @param loginUser
     * @return
     */
    @PostMapping("{tenantId}/api/auth/login")
    public Object tenantlogin(@PathVariable("tenantId") String tenantId, @RequestBody User loginUser) {
        loginUser.setCompanyId(tenantId);
        return authService.login(loginUser);
    }

    /**
     * 普通用户登录
     * @param loginUser
     * @return
     */
    @PostMapping("/api/auth/login")
    public Object adminLogin(@RequestBody User loginUser) {
        return authService.login(loginUser);
    }

    /**
     * 用户登出
     */
    @GetMapping("/api/auth/logout")
    public void logout() {
        authService.logout();
    }

    /**
     * 获取验证码
     * @param response
     * @throws Exception
     */
    @GetMapping("/api/auth/verifycode")
    public void getVerifycode(HttpServletResponse response) throws Exception {
        String verifyId = IdWorker.get32UUID();

        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        response.setHeader(shiroProperties.getBase().getVerifyCode().getId(), verifyId);

        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            ImageIO.write(authService.getVerifycode(verifyId), "jpg", out);
        } finally {
            if (null != out) {
                out.close();
            }
        }
    }

    /**
     * 查询登录历史
     * @param userId
     * @return
     */
    @RequiresPermissions("sys:auth:history:query")
    @GetMapping("/api/auth/history")
    public Object getAuthHistory(
            @RequestParam(value = "userId", required = false) String userId) {
        PagingUtils.pagingIfExist(request);
        if (StringUtils.isEmpty(userId)) {
            return loginLogService.selectList(new EntityWrapper<LoginLog>().orderBy(LoginLog.LOGINDATE));
        }
        return loginLogService.selectList(new EntityWrapper<LoginLog>().eq(LoginLog.USERID, userId)
                                                                       .orderBy(LoginLog.LOGINDATE));
    }
}
